package com.example.esp8266.activity.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.esp8266.R;
import com.example.esp8266.activity.MainActivity;
import com.example.esp8266.activity.adapter.MyAdapter;
import com.example.esp8266.activity.bean.Product;
import com.example.esp8266.activity.bean.ProductInfo;
import com.example.esp8266.activity.productSQLlist.MyOpenHelper;
import com.example.esp8266.activity.productSQLlist.ProductInfoHelper;
import com.example.esp8266.activity.utile.MouthpieceTool;
import com.example.esp8266.activity.utile.ScreenUtils;
import com.example.esp8266.activity.utile.SocketLink;
import com.example.esp8266.activity.utile.StringUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CommonFragment extends Fragment implements View.OnClickListener{
    View view;
    private SocketLink socketLink;
    private MouthpieceTool mouthpieceTool;
    MainActivity mainActivity;
    private List<Product> list = new ArrayList<>();
    Button bt_addProduct,bt_clearInfo,bt_weigh,bt_viewData,bt_peel,bt_calibrate,bt_productTotal;
    TextView tv_productName,tv_productPrice,tv_sum,tv_weight,tv_total;
    LinearLayout parent_layout,parent2_layout;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_common, container, false);
        init();
        mainActivity = (MainActivity) getActivity();
        if (mainActivity != null){
            socketLink = mainActivity.getSocketLink();
            mouthpieceTool = mainActivity.getMouthpieceTool();
        }
        if (!EventBus.getDefault().isRegistered(this)) { //判断是否注册，避免重复注册
            EventBus.getDefault().register(this);
        }
        setHintKeyboardView(view);// 关闭软键盘
        return view;
    }
    MyOpenHelper myOpenHelper;
    ProductInfoHelper productInfoHelper;
    public void init(){
        tv_total = view.findViewById(R.id.tv_total);
        tv_weight = view.findViewById(R.id.tv_weight);
        bt_productTotal = view.findViewById(R.id.bt_productTotal);
        bt_productTotal.setOnClickListener(this);
        bt_calibrate = view.findViewById(R.id.bt_calibrate);
        bt_calibrate.setOnClickListener(this);
        bt_peel = view.findViewById(R.id.bt_peel);
        bt_peel.setOnClickListener(this);
        bt_viewData = view.findViewById(R.id.bt_viewData);
        bt_viewData.setOnClickListener(this);
        tv_productPrice = view.findViewById(R.id.tv_productPrice);
        tv_productName = view.findViewById(R.id.tv_productName);
        bt_weigh = view.findViewById(R.id.bt_weigh);
        bt_weigh.setOnClickListener(this);
        bt_clearInfo = view.findViewById(R.id.bt_clearInfo);
        bt_clearInfo.setOnClickListener(this);
        bt_addProduct = view.findViewById(R.id.bt_addProduct);
        bt_addProduct.setOnClickListener(this);

        myOpenHelper = new MyOpenHelper(getContext());
        //打开数据库
        SQLiteDatabase sqLiteDatabase = myOpenHelper.getReadableDatabase();
        //关闭数据库
        sqLiteDatabase.close();

        productInfoHelper = new ProductInfoHelper(getContext());
        SQLiteDatabase sqLiteDatabase2 = productInfoHelper.getReadableDatabase();
        //关闭数据库
        sqLiteDatabase2.close();

        //获取控件
        productData();
    }
    public void productData(){
        //添加数据到list里
        ArrayList<Product> productList = myOpenHelper.readAllData();
        for (int i = 0; i < productList.size() ; i++) {
            Product product = new Product();
            product.setProductName(productList.get(i).getProductName());
            product.setProductId(productList.get(i).getProductId());
            list.add(product);
        }
        //  网格 布局
        RecyclerView recyclerView = view.findViewById(R.id.recyclerV);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),3);
        recyclerView.setLayoutManager(gridLayoutManager);

        MyAdapter myAdapter =  new MyAdapter(list,getContext());
        recyclerView.setAdapter(myAdapter);
        //点击事件
        myAdapter.setMonRecyclerItemClickListener(new MyAdapter.onRecyclerItemClickListener(){
            @Override
            public void onRecyclerItemClick(int position) {
                tv_weight.setText("");
                tv_total.setText("");
                Log.e("点击llll","hello, recycler"+position);
                System.out.println("--点击：--"+list.get(position).getProductName()+list.get(position).getProductId());
                String productName = list.get(position).getProductName();
                Product product = new Product();
                product.setProductName(String.valueOf(list.get(position).getProductId()));
                ArrayList<Product> productList = myOpenHelper.selectByProductName(product);
                System.out.println("---- 条件查询 ----"+productList);
                tv_productName.setText(productList.get(0).getProductName());
                tv_productPrice.setText(productList.get(0).getProductPrice());
            }
        });
        myAdapter.setLongMonRecyclerItemClickListener(new MyAdapter.onLongRecyclerItemClickListener() {
            @Override
            public void onLongRecyclerItemClick(final int position) {
                System.out.println("------ 长按事件 ---------"+list.get(position).getProductName());
                //   长按 删除 数据库 信息
                final AlertDialog alertDialog=new AlertDialog.Builder(getContext())
                    .setIcon(R.mipmap.xuanzhong)
                        .setTitle("是否删除商品")
                        .setMessage("已选中："+list.get(position).getProductName())
                        .setNegativeButton("留着吧", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //执行代码
                            }
                        })
                        .setPositiveButton("不要了", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogInterface, int i) {
                                System.out.println("----点击了确定 ---");
                                try {
                                    Product p = new Product();
                                    p.setProductId(list.get(position).getProductId());
                                    myOpenHelper.delectProject(p);
                                }catch (Exception e){
                                    System.out.println("--异常：---"+e);
                                }finally {
                                    if (list.size() > 0){
                                        list.clear();
                                    }
                                    productData();
                                }
                            }
                        })
                        .create();
                alertDialog.show();
            }
        });
    }

    List<Product> plist = new ArrayList<>();
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_addProduct:  // 添加商品
                showPopupWindow();
                break;
            case R.id.bt_clearInfo:   // 清除

                break;
            case R.id.bt_weigh:  //  称重
                String price = tv_productPrice.getText().toString();
                if(tv_productName.getText().toString().equals("")){
                    Toast.makeText(mainActivity, "您还没选择商品！！！", Toast.LENGTH_SHORT).show();
                }else {
                    tv_total.setText("");
                    Double d = Double.valueOf(price);
                    Map<String,Object> map = new HashMap<>();
                    map.put("func_code",1);
                    map.put("param1",d);
                    map.put("param2","");
                    final String s = com.alibaba.fastjson.JSONObject.toJSONString(map);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            socketLink.sendJson(s);
                        }
                    },300);

                    System.out.println("------map------"+map);
                }
//                final String name = tv_productName.getText().toString();
//                final String price = tv_productPrice.getText().toString();
//                tv_weight.setText("2");
//                final Double d_weight = Double.valueOf(tv_weight.getText().toString());
//                tv_total.setText(String.valueOf(multiply(d_weight, Double.valueOf(price))));
//                final String sum = tv_total.getText().toString();
//
//                plist.add(new Product(name,price,String.valueOf(d_weight),sum));
                break;
            case R.id.bt_viewData:  // 查看数据
                System.out.println("--数据--");
                showViewDtaPopup();
                forViewData();
                break;
            case R.id.bt_peel:    // 去皮
                Map<String,Object> map = new HashMap<>();
                map.put("func_code",2);
                map.put("param1",0);
                map.put("param2",0);
                System.out.println(map+"----map ------");
                String s = com.alibaba.fastjson.JSONObject.toJSONString(map);
                socketLink.sendJson(s);
                break;
            case R.id.bt_calibrate:  // 校准
                showKgPopupWindow();
                break;
            case R.id.bt_productTotal:  //  合计
                System.out.println("-----合计-----");
                if (plist.size() > 0){
                    Map<String,Object> map2 = new HashMap<>();
                    map2.put("func_code",5);
                    map2.put("param1",0);
                    map2.put("param2",0);
                    System.out.println(map2+"----map ------");
                    String s2 = com.alibaba.fastjson.JSONObject.toJSONString(map2);
                    socketLink.sendJson(s2);
                }
                showSumPopupwindow();
                forView();
                getViewValue();
                report();
                break;
            default:
                break;
        }
    }
    @Override
    public void onStart() {
        super.onStart();
    }

    //接收wifi回传指令
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(String str){
        System.out.println("----普通配置-------"+str+"------------");

        final String s = str;

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    double param1Value = jsonObject.getDouble("param1");
                    double param2Value = jsonObject.getDouble("param2");

                    System.out.println("param1 的值是: " + param1Value);
                final String name = tv_productName.getText().toString();
                final String price = tv_productPrice.getText().toString();
                tv_weight.setText(String.valueOf(param1Value));

                final String weight = tv_weight.getText().toString();

                tv_total.setText(String.valueOf(param2Value));

//                final Double d_weight = Double.valueOf(tv_weight.getText().toString());
//                tv_total.setText(String.valueOf(multiply(d_weight, Double.valueOf(price))));
                final String sum = tv_total.getText().toString();
                plist.add(new Product(name,price,weight,sum));



                } catch (JSONException e) {
                    // 处理 JSON 解析异常
                    e.printStackTrace();
                }
            }
        },300);



    }

    PopupWindow kgPopupWindow;
    public void  showKgPopupWindow(){
        View kgview = getLayoutInflater().inflate(R.layout.add_kg,null);
        final EditText et_kg = kgview.findViewById(R.id.et_kg);
        Button bt_kg = kgview.findViewById(R.id.bt_kg);
        int width = ScreenUtils.getWidth(getContext());
        kgPopupWindow = new PopupWindow
                (kgview, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        kgPopupWindow.setTouchable(true);
        kgPopupWindow.setFocusable(true);
        kgPopupWindow.setOutsideTouchable(true);

        bt_kg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String str_kg = et_kg.getText().toString();
                if (str_kg.equals("")){
                    Toast.makeText(getContext(), "上报信息为空！！！", Toast.LENGTH_SHORT).show();
                }else {
                    Map<String,Object> map2 = new HashMap<>();
                    map2.put("func_code",3);
                    map2.put("param1",0);
                    map2.put("param2",Integer.valueOf(str_kg));
                    System.out.println(map2+"----map ------");
                    String s2 = com.alibaba.fastjson.JSONObject.toJSONString(map2);
                    socketLink.sendJson(s2);
                    et_kg.setText("");
                }
            }
        });
        kgPopupWindow.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER,0,0);

    }


    public void forView(){
        if (plist.size() > 0){
            for (int i = 0; i < plist.size(); i++) {
                // 创建新的LinearLayout
                LinearLayout linearLayout = new LinearLayout(getContext());
                linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        dpToPx(30));
                layoutParams.setMargins(0,0,0,0);
                linearLayout.setLayoutParams(layoutParams);
                // 创建 TextView
                TextView textView = new TextView(getActivity());
                textView.setText(plist.get(i).getProductName());
                textView.setTextSize(15);
                textView.setGravity(Gravity.CENTER);
                LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
                textView.setLayoutParams(textViewParams);

                TextView textView2 = new TextView(getActivity());
                textView2.setText(plist.get(i).getProductPrice());
                textView2.setTextSize(15);
                textView2.setGravity(Gravity.CENTER);
                LinearLayout.LayoutParams textViewParams2 = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
                textView2.setLayoutParams(textViewParams2);

                TextView textView3 = new TextView(getActivity());
                textView3.setText(plist.get(i).getProductWeight());
                textView3.setTextSize(15);
                textView3.setGravity(Gravity.CENTER);
                LinearLayout.LayoutParams textViewParams3 = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
                textView3.setLayoutParams(textViewParams3);

                TextView textView4 = new TextView(getActivity());
                textView4.setText(plist.get(i).getProductTotal());
                textView4.setTextSize(15);
                textView4.setGravity(Gravity.CENTER);
                LinearLayout.LayoutParams textViewParams4 = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
                textView4.setLayoutParams(textViewParams4);

                // 将TextView添加到LinearLayout中
                linearLayout.addView(textView);
                linearLayout.addView(textView2);
                linearLayout.addView(textView3);
                linearLayout.addView(textView4);

                // 将LinearLayout添加到容器布局中
                parent_layout.addView(linearLayout);
            }
        }else {
            Toast.makeText(mainActivity, "还没有进行称重！！", Toast.LENGTH_SHORT).show();
        }
    }
    //  添加到数据库
    public void report(){
        for (int i = 0; i < plist.size(); i++) {
            ProductInfo productInfo = new ProductInfo();
            productInfo.setName(plist.get(i).getProductName());
            productInfo.setPrice(plist.get(i).getProductPrice());
            productInfo.setWeight(plist.get(i).getProductWeight());
            productInfo.setTotal(plist.get(i).getProductTotal());
            productInfoHelper.add(productInfo);
        }
        if (plist.size() > 0){
            plist.clear();
        }
    }
    Double sum ;
    // 获取 值
    public void getViewValue(){
        sum = 0.0;
        ViewGroup parent_layout = popview.findViewById(R.id.parent_layout);
        for (int i = 0; i < parent_layout.getChildCount(); i++) {
            LinearLayout linearLayout = (LinearLayout) parent_layout.getChildAt(i);
            TextView textView = (TextView) linearLayout.getChildAt(3);
            String textViewText = textView.getText().toString();
            if (textViewText.length() > 0){
                Double d = Double.valueOf(textViewText);
                sum = add(sum,d);
            }
        }
        tv_sum.setText(String.valueOf(sum));
    }
    public void forViewData(){
        ArrayList<ProductInfo> productInfoList = productInfoHelper.selectAll();
        System.out.println("----productInfoList------"+productInfoList);
        if (productInfoList.size() > 0){
            for (int i = 0; i < productInfoList.size(); i++) {
                LinearLayout linearLayout = new LinearLayout(getContext());
                linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        dpToPx(30));
                layoutParams.setMargins(0,0,0,0);
                linearLayout.setLayoutParams(layoutParams);
                // 创建 TextView
                TextView textView = new TextView(getActivity());
                textView.setText(productInfoList.get(i).getName());
                textView.setTextSize(15);
                textView.setGravity(Gravity.CENTER);
                LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
                textView.setLayoutParams(textViewParams);

                TextView textView2 = new TextView(getActivity());
                textView2.setText(productInfoList.get(i).getPrice());
                textView2.setTextSize(15);
                textView2.setGravity(Gravity.CENTER);
                LinearLayout.LayoutParams textViewParams2 = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
                textView2.setLayoutParams(textViewParams2);

                TextView textView3 = new TextView(getActivity());
                textView3.setText(productInfoList.get(i).getWeight());
                textView3.setTextSize(15);
                textView3.setGravity(Gravity.CENTER);
                LinearLayout.LayoutParams textViewParams3 = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
                textView3.setLayoutParams(textViewParams3);

                TextView textView4 = new TextView(getActivity());
                textView4.setText(productInfoList.get(i).getTotal());
                textView4.setTextSize(15);
                textView4.setGravity(Gravity.CENTER);
                LinearLayout.LayoutParams textViewParams4 = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
                textView4.setLayoutParams(textViewParams4);

                // 将TextView添加到LinearLayout中
                linearLayout.addView(textView);
                linearLayout.addView(textView2);
                linearLayout.addView(textView3);
                linearLayout.addView(textView4);

                // 将LinearLayout添加到容器布局中
                parent2_layout.addView(linearLayout);
            }
        }else {
            Toast.makeText(getContext(), "数据库还没有数据哦!", Toast.LENGTH_SHORT).show();
        }
    }
    //  两数 相加
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }
    /**
     * 精确的浮点乘法运算
     * */
    public static double multiply(double data1, double data2) {
        BigDecimal b1 = BigDecimal.valueOf(data1);
        BigDecimal b2 = BigDecimal.valueOf(data2);
        return b1.multiply(b2).doubleValue();
    }

    PopupWindow viewDtaPopup;
    public void showViewDtaPopup(){
        View view = getLayoutInflater().inflate(R.layout.view_data,null);
        parent2_layout = view.findViewById(R.id.parent2_layout);
        int width = ScreenUtils.getWidth(getContext());
        viewDtaPopup = new PopupWindow
                (view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        viewDtaPopup.setTouchable(true);
        viewDtaPopup.setFocusable(true);
        viewDtaPopup.setOutsideTouchable(true);
        viewDtaPopup.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER,0,0);
    }
    //   信息
    PopupWindow sumPopupwindow;
    View popview;
    public void showSumPopupwindow(){
        popview = getLayoutInflater().inflate(R.layout.product_info,null);
        parent_layout = popview.findViewById(R.id.parent_layout);
        tv_sum = popview.findViewById(R.id.tv_sum);
        final EditText et_changeMoney = popview.findViewById(R.id.et_changeMoney);
        final TextView tv_money = popview.findViewById(R.id.tv_money);
        Button bt_money = popview.findViewById(R.id.bt_money);

        int width = ScreenUtils.getWidth(getContext());
        sumPopupwindow = new PopupWindow
                (popview, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        sumPopupwindow.setTouchable(true);
        sumPopupwindow.setFocusable(true);
        sumPopupwindow.setOutsideTouchable(true);
        bt_money.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String changeMoney = et_changeMoney.getText().toString();
                String s = tv_sum.getText().toString();
                Double d1 = Double.valueOf(s);
                Double d2 = Double.valueOf(changeMoney);
                Double sub = sub(d2,d1);
                tv_money.setText(String.valueOf(sub));


            }
        });


        sumPopupwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                tv_productName.setText("");
                tv_productPrice.setText("");
                tv_weight.setText("");
                tv_total.setText("");
                //  zhaoling
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        showMoneyPop();
//                    }
//                },300);
            }
        });
        sumPopupwindow.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER,0,0);
    }
    PopupWindow moneyPOP;
    public void showMoneyPop(){
        View view = getLayoutInflater().inflate(R.layout.change_money,null);
        final EditText et_changeMoney = view.findViewById(R.id.et_changeMoney);
        Button bt_money = view.findViewById(R.id.bt_money);
        int width = ScreenUtils.getWidth(getContext());
        moneyPOP = new PopupWindow
                (view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        moneyPOP.setTouchable(true);
        moneyPOP.setFocusable(true);
        moneyPOP.setOutsideTouchable(true);
        bt_money.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String str = et_changeMoney.getText().toString();
                if (str.equals("")){
                    Toast.makeText(getContext(), "请输入金额", Toast.LENGTH_SHORT).show();
                }else {
                    String s = tv_sum.getText().toString();
                    Double d1 = Double.valueOf(s);
                    Double d2 = Double.valueOf(str);
                    Double sub = sub(d1,d2);
                    System.out.println("----找零 -----"+sub);
                    Toast.makeText(getContext(), "应找金额"+sub, Toast.LENGTH_SHORT).show();
                }

            }
        });
        moneyPOP.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER,0,0);
    }
    //     减法
    public double sub(double a,double b)
    {
        BigDecimal b1 = new BigDecimal(Double.toString(a));
        BigDecimal b2 = new BigDecimal(Double.toString(b));
        return b1.subtract(b2).doubleValue();
    }


    PopupWindow popupWindow;
    public void showPopupWindow(){
        View view = getLayoutInflater().inflate(R.layout.add_product,null);
        int width = ScreenUtils.getWidth(getContext());
        popupWindow = new PopupWindow
                (view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        final EditText productName_ET =  view.findViewById(R.id.productName_ET);
        final EditText productPrice_ET = view.findViewById(R.id.productPrice_ET);
        productPrice_ET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                LogU.d("beforeTextChanged=" + s.toString());
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String money = s.toString();
                if (money.length() > 0) {
                    int i = money.indexOf(".");
                    int i1 = money.lastIndexOf(".");
//                    LogU.d("onTextChanged=" + money + ",i=" + i + ",i1=" + i1);
                    if (i > 0) {
                        String substring = "";
                        if (i != i1) {
                            substring = s.toString().substring(0, i1);
                            productPrice_ET.setText(substring);
                            productPrice_ET.setSelection(substring.length());
                        } else if (i == i1 && money.length() - i > 3) {
                            substring = money.substring(0, i + 3);
                            productPrice_ET.setText(substring);
                            productPrice_ET.setSelection(substring.length());
                        }
                    } else if (i == 0) {
                        productPrice_ET.setText("");
                    }
                }

            }
            @Override
            public void afterTextChanged(Editable s) {
//                LogU.d("afterTextChanged=" + s.toString());

            }
        });
        Button bt = view.findViewById(R.id.bt);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = productName_ET.getText().toString();
                String price = productPrice_ET.getText().toString();
                if (name.equals("") || price.equals("") ){
                    Toast.makeText(getContext(), "填报数据 不为空！！", Toast.LENGTH_SHORT).show();
                }else {
                    System.out.println("---- 提交 --------"+price);
                    Double d = Double.valueOf(price);
                    Product product = new Product();
                    product.setProductName(name);
                    product.setProductPrice(String.valueOf(d));
                    try {
                        myOpenHelper.add(product);
                    }catch (Exception e){
                        Toast.makeText(getContext(), "异常："+e, Toast.LENGTH_SHORT).show();
                    }finally {
                        if (list.size()>0){
                            list.clear();
                        }
                        productData();
                        popupWindow.dismiss();
                    }
                }

            }
        });
        popupWindow.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER,0,0);
    }

    public static Map<String,Object> mapStringToMap(String str){
        str = str.substring(1, str.length()-1);
        String[] strs = str.split(",");
        Map<String,Object> map = new HashMap<>();
        for (String string : strs) {
            String key = string.split("=")[0];
            String value = string.split("=")[1];
            // 去掉头部空格
            String key1 = key.trim();
            String value1 = value.trim();
            map.put(key1, value1);
        }
        return map;
    }

    //    dp  转化为  像素
    public int dpToPx(int dp) {
        float density = getResources().getDisplayMetrics().density;
        return Math.round((float) dp * density);
    }
    //成功提示弹窗
    public Toast popWindowSuccess(final String content) {
        Toast  toast =  Toast.makeText(getContext(), content,
                Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        return toast;
    }
    //失败提示弹窗
    public Toast popWindowFail(final String content) {
        Toast  toast =  Toast.makeText(getContext(), content,
                Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        return toast;
    }

    // 将16进制 ASCII转成字符串
    public static String asciiToString(String str) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < str.length(); i += 2) {
            stringBuilder.append((char) Integer.parseInt(str.substring(i, i + 2), 16));
        }
        return stringBuilder.toString();
    }

    //转换接收回来的十六进制
    public int getTransformation(String str){
        int length = str.length();
        String info = str.substring(8,length-4);
        int num = Integer.valueOf(info,16);
        return num;
    }
    public double getTransformation3(String str){
        int length = str.length();
        String weight = str.substring(8,length-4);
        int num = Integer.valueOf(weight,16);
        double sum=Double.parseDouble(String.valueOf(num))/10;
        return sum;
    }
    //转换接收到的投口重量
    public double getFeedingWeight(String str){
        int length = str.length();
        String weight = str.substring(10,length-4);
        int num = Integer.valueOf(weight,16);
        double sum=Double.parseDouble(String.valueOf(num))/10;
        return sum;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    /**
     * 设置点击软键盘之外区域，软键盘消失
     *
     * @param view
     */
    public void setHintKeyboardView(View view) {
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hintKeyboard(getActivity());
                    return false;
                }
            });
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setHintKeyboardView(innerView);
            }
        }
    }
    public  void hintKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && activity.getCurrentFocus() != null) {
            if (activity.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
}
